package com.syxx.oa.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.syxx.oa.domain.Department;
import com.test.jbpm.Pager;
import com.test.jbpm.PagerContext;
import com.test.jbpm.dao.impl.BaseDao;
@Repository
public class DepartMentDao extends BaseDao {

	public void addOrUpdate(Department dep) {
		try {
			getHibernateTemplate().saveOrUpdate(dep);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void del(final Long depId) {
		Department dep = (Department)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException,SQLException {
				return session.createQuery("from Department d where d.depId=?")
					.setParameter(0, depId)
					.uniqueResult();
			}	
		});
		getHibernateTemplate().delete(dep);
	}

	public Department findDepById(final Long depId) {
//		UUID uuid2=UUID.fromString(depId);
		
		return (Department)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				return session.createQuery("from Department d where d.depId=?")
							.setParameter(0, depId)
							.uniqueResult();
			}
		});
		
//		Department dep = (Department)getHibernateTemplate().load(Department.class, uuid2);
//		return dep;
	}

	@SuppressWarnings("unchecked")
	public Pager<Department> findDepList() {
		return findData("from Department");
	}
	public List<Department> findDepList(final HashMap<String, String> key){
		@SuppressWarnings("unchecked")
		List<Department> list = getHibernateTemplate().executeFind(new HibernateCallback() {
			
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql = "from Department d";
				if(key != null && !key.isEmpty()){
					hql += " where ";
					int i=0;
					for (String k : key.keySet()) {
						if(i==key.keySet().size()-1){
							hql+=" (d."+k+"=?) ";
						}else{
							hql+=" (d."+k+"=?) and ";
						}
						i++;
					}
				}
				Query query = session.createQuery(hql);
				if(key != null && !key.isEmpty()){
					int i=0;
					for (String value : key.values()) {
						query.setParameter(i, value);
						i++;
					}
				}
				return query.list();
			}
		});
		return list;
	}

	
}
